package com.hd.common.page.factory;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author chentl
 * @version V1.0
 * @Project 交通运输第三方监测平台
 * @Title PageFactory.java
 * @Description 分页工厂类
 * @Package com.hd.common.page.factory
 * @date 2020/12/24 11:31 上午
 * @Copyright: 深圳市宏电技术股份有限公司 All rights reserved.
 */
public class PageFactory<T> {

    public static final int MAX_PAGESIZE = 50;
    public static final int DEFAULT_SIZE = 10;
    public static final int DEFAULT_OFFSET = 1;
    public static final String SIZE = "size";
    public static final String CURRENT = "current";

    public Page<T> defaultPage() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //每页多少条数据
        String limitStr = request.getParameter(SIZE);
        int limit = DEFAULT_SIZE;
        if (StringUtils.isNotBlank(limitStr)) {
            limit = Integer.parseInt(limitStr);
            if (limit > MAX_PAGESIZE) {
                limit = MAX_PAGESIZE;
            }
        }
        //第几页
        String offsetStr = request.getParameter(CURRENT);
        int offset = DEFAULT_OFFSET;
        if (StringUtils.isNotBlank(offsetStr)) {
            offset = Integer.parseInt(offsetStr);
        }
        Page<T> page = new Page<>(offset, limit);

        return page;
    }
}
